package com.qinghe.utils.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * 对象的序列化与反序列化
 * 
 * @author longfei
 */
public class SerializableUtil implements Serializable {

	private static final long serialVersionUID = 8655522439338884550L;

	/**
     * 对象的序列化，把Java对象转换为字节序列。
     * @param obj Java对象
     * @return byte[]
     */
	public static byte[] serialize(Object obj) {
		byte[] bytes = new byte[1024];
		try {
			ByteArrayOutputStream bo = new ByteArrayOutputStream();
			ObjectOutputStream oo = new ObjectOutputStream(bo);
			oo.writeObject(obj);

			bytes = bo.toByteArray();

			bo.close();
			oo.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bytes;
	}

	/**
     * 对象的反序列化，把字节序列恢复为Java对象。
     * @param bytes 字节数组
     * @return Object
     */
	public static Object deSerialize(byte[] bytes) {
		java.lang.Object obj = new java.lang.Object();
		try {
			ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
			ObjectInputStream oi = new ObjectInputStream(bi);

			obj = oi.readObject();

			bi.close();
			oi.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}

}
